<template>
    <div id="app">
        <!-- 筛选条件 -->
        <div class="filter-container">
            <div class="filter-row">
                <div class="filter-group">
                    <label class="filter-label">年份选择</label>
                    <el-select v-model="queryParams.selectedYear" placeholder="请选择年份" style="width:100%">
                        <el-option v-for="year in years" :key="year" :label="year" :value="year">
                        </el-option>
                    </el-select>
                </div>

                <div class="filter-group">
                    <label class="filter-label">月份选择</label>
                    <el-select v-model="queryParams.selectedMonths" multiple placeholder="请选择月份" style="width:100%">
                        <el-option v-for="month in months" :key="month.value" :label="month.label" :value="month.value">
                        </el-option>
                    </el-select>
                </div>

                <div class="filter-group">
                    <label class="filter-label">产线选择</label>
                    <el-select v-model="queryParams.selectedLines" multiple placeholder="请选择产线" style="width:100%">
                        <el-option v-for="line in productionLines" :key="line" :label="line" :value="line">
                        </el-option>
                    </el-select>
                </div>
            </div>

            <div class="action-buttons">
                <el-button type="primary" icon="el-icon-search" class="hard-buttons" @click="query">查询数据</el-button>

                <el-button icon="el-icon-refresh" class="hard-buttons" @click="re">重置条件</el-button>
                <el-tooltip class="box-item" effect="dark" content="请查询后再导出" placement="bottom">
                    <el-button type="success" icon="el-icon-download" class="hard-buttons"
                        @click="handleExport">导出数据</el-button></el-tooltip>
                <!-- 导入Excel -->
                <el-upload action="" :auto-upload="false" :show-file-list="false" :on-change="handleImport"
                    accept=".xlsx,.xls" v-hasPermi="['smtdashboard:smttable:handleImport']">
                    <el-button type="warning" :loading="importLoading">
                        <i class="el-icon-upload" v-if="!importLoading"></i>
                        {{ importLoading ? '导入中...' : '导入Excel' }}
                    </el-button>
                    <div slot="tip" class="el-upload__tip"><!-- 下载模板 -->
                        <el-button type="text" @click="downloadTemplate" :loading="templateLoading">
                            {{ templateLoading ? '模板下载中...' : '下载导入模板' }}
                        </el-button>
                    </div>
                </el-upload>
            </div>
        </div>

        <!-- 加载遮罩层 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <div class="loading-text">{{ loadingText }}</div>
        </div>


        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" height="600px" >
            <!-- 基础信息 -->
            <el-table-column fixed label="year" prop="year" align="center" />
            <el-table-column fixed label="month" prop="month" align="center" />
            <el-table-column fixed label="line" prop="line" align="center" />

            <!-- Claim 相关指标 -->
            <el-table-column label="claim-Total" prop="claimTotal" align="center" :formatter="formatNumber" />
            <el-table-column label="claim-H1" prop="claimH1" align="center" :formatter="formatNumber" />
            <el-table-column label="claim-C" prop="claimC" align="center" :formatter="formatNumber" />

            <!-- Sorting Fee -->
            <el-table-column label="sorting-Fee-Total" prop="sortingFeeTotal" align="center"
                :formatter="formatNumber" />
            <el-table-column label="sorting-Fee-IQC" prop="sortingFeeIqc" align="center" :formatter="formatNumber" />
            <el-table-column label="sorting-Fee-Claim" prop="sortingFeeClaim" align="center"
                :formatter="formatNumber" />

            <!-- 生产指标 -->
            <el-table-column label="input-Amount" prop="inputAmount" align="center" :formatter="formatNumber" />
            <el-table-column label="scarp-Amount" prop="scarpAmount" align="center" :formatter="formatNumber" />

            <!-- 百分比字段添加格式化 -->
            <el-table-column label="scarp-Rate" prop="scarpRate" align="center" :formatter="formatPercent" />
            <el-table-column label="non-Conformity" prop="nonConformity" align="center" :formatter="formatNumber" />
            <el-table-column label="capa" prop="capa" align="center" :formatter="formatNumber" />

            <!-- OQC 检验 -->
            <el-table-column label="oqc-Scan-QTY" prop="oqcScanQty" align="center" :formatter="formatNumber" />
            <el-table-column label="oqc-Scan-NG-QTY" prop="oqcScanNgQty" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="oqc-Scan-NG" prop="oqcScanNg" align="center" :formatter="formatPercent" />

            <el-table-column label="oqc-Insp-Lot" prop="oqcInspLot" align="center" :formatter="formatNumber" />
            <el-table-column label="oqc-Reject-Lot" prop="oqcRejectLot" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="oqc-Lrr" prop="oqcLrr" align="center" :formatter="formatPercent" />

            <el-table-column label="oqc-Insp-QTY" prop="oqcInspQty" align="center" :formatter="formatNumber" />
            <el-table-column label="oqc-NG-QTY" prop="oqcNgQty" align="center" :formatter="formatNumber" />
            <el-table-column label="oqc-Dppm" prop="oqcDppm" align="center" :formatter="formatNumber" />

            <!-- OBA 检验 -->
            <el-table-column label="oba-Times" prop="obaTimes" align="center" :formatter="formatNumber" />
            <el-table-column label="oba-Reject-Time" prop="obaRejectTime" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="oba-Ng" prop="obaNg" align="center" :formatter="formatPercent" />

            <!-- IPQC 检验 -->
            <el-table-column label="ipqc-Findings" prop="ipqcFindings" align="center" :formatter="formatNumber" />
            <el-table-column label="ipqc-Major" prop="ipqcMajor" align="center" :formatter="formatNumber" />
            <el-table-column label="ipqc-Minor" prop="ipqcMinor" align="center" :formatter="formatNumber" />
            <el-table-column label="ipqc-Close-Mil" prop="ipqcCloseMil" align="center" :formatter="formatNumber" />
            <el-table-column label="ipqc-Close-Rate" prop="ipqcCloseRate" align="center" :formatter="formatPercent" />

            <!-- 第三方检验 -->
            <el-table-column label="3rd-party-Findings" prop="partyFindings3Rd" align="center"
                :formatter="formatNumber" />
            <el-table-column label="3rd-party-Major" prop="partyMajor3Rd" align="center" :formatter="formatNumber" />
            <el-table-column label="3rd-party-Minor" prop="partyMinor3Rd" align="center" :formatter="formatNumber" />
            <el-table-column label="3rd-party-Close-Mil" prop="partyCloseMil3Rd" align="center"
                :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="3rd-party-Close-Rate" prop="partyCloseRate3Rd" align="center"
                :formatter="formatPercent" />

            <!-- 合规性 -->
            <el-table-column label="compliance-Total" prop="complianceTotal" align="center" :formatter="formatNumber" />
            <el-table-column label="comp-Customer" prop="compCustomer" align="center" :formatter="formatNumber" />
            <el-table-column label="comp-Internal" prop="compInternal" align="center" :formatter="formatNumber" />

            <!-- FOX 指标 -->
            <el-table-column label="fox-Total" prop="foxTotal" align="center" :formatter="formatNumber" />
            <el-table-column label="fox-ICT" prop="foxIct" align="center" :formatter="formatNumber" />
            <el-table-column label="fox-SPI" prop="foxSpi" align="center" :formatter="formatNumber" />
            <el-table-column label="fox-Fpy" prop="foxFpy" align="center" :formatter="formatPercent" />
            <el-table-column label="fox-Delay" prop="foxDelay" align="center" :formatter="formatNumber" />

            <!-- SPI 测试 -->
            <el-table-column label="spi-Input" prop="spiInput" align="center" :formatter="formatNumber" />
            <el-table-column label="spi-Output" prop="spiOutput" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="spi-Fpy" prop="spiFpy" align="center" :formatter="formatPercent" />

            <!-- AOI 测试 -->
            <el-table-column label="aoi-Input" prop="aoiInput" align="center" :formatter="formatNumber" />
            <el-table-column label="aoi-Fp-Qty" prop="aoiFpQty" align="center" :formatter="formatNumber" />
            <el-table-column label="aoi-Output" prop="aoiOutput" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="aoi-Fpy" prop="aoiFpy" align="center" :formatter="formatPercent" />
            <el-table-column label="aoi-Fy" prop="aoiFy" align="center" :formatter="formatPercent" />

            <!-- ICT 测试 -->
            <el-table-column label="ict-Input" prop="ictInput" align="center" :formatter="formatNumber" />
            <el-table-column label="ict-Fp-Qty" prop="ictFpQty" align="center" :formatter="formatNumber" />
            <el-table-column label="ict-Output" prop="ictOutput" align="center" :formatter="formatNumber" />

            <!-- 百分比字段 -->
            <el-table-column label="ict-Fpy" prop="ictFpy" align="center" :formatter="formatPercent" />
            <el-table-column label="ict-Fy" prop="ictFy" align="center" :formatter="formatPercent" />

            <!-- 追加动态字段 -->
            <el-table-column label="ipqc-Latest-Close-Mil" prop="ipqcLatestCloseMil" align="center" :formatter="formatNumber" />
            <el-table-column label="party-Latest-Close-Mil" prop="partyLatestCloseMil" align="center" :formatter="formatNumber" />
        </el-table>

        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="query" />
    </div>
</template>

<script>
import { importExcel, exportctTemplate, querytable, dashboardExport } from "@/api/smtdashboard/smttable"

export default {
    name: "DashboardData",
    data() {
        return {
            //表格数据
            tableData: [],
            //查询参数
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                selectedYear: '',
                selectedMonths: [],
                selectedLines: [],
            },
            data: {},
            years: [],
            months: [
                { value: 'Jan', label: '1月' },
                { value: 'Feb', label: '2月' },
                { value: 'Mar', label: '3月' },
                { value: 'Apr', label: '4月' },
                { value: 'May', label: '5月' },
                { value: 'Jun', label: '6月' },
                { value: 'Jul', label: '7月' },
                { value: 'Aug', label: '8月' },
                { value: 'Sept', label: '9月' },
                { value: 'Oct', label: '10月' },
                { value: 'Nov', label: '11月' },
                { value: 'Dec', label: '12月' }
            ],
            productionLines: ['#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9', '#10', '#11', '#12', '#13', '#14', '#15'],
            importLoading: false,
            templateLoading: false,
            loading: false,
            loadingText: '处理中...'
        }
    },

    created() {
        this.shortYear()
    },
    methods: {
        re() {
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.queryParams.selectedMonths = []
            this.queryParams.selectedLines = []
        },
        //excel使用
        handleExport() {
            this.$confirm("确认导出基础数据吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                // 调用导出接口
                dashboardExport().then(response => {
                    const url = URL.createObjectURL(new Blob([response]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', 'SMTDashboard基础数据.xlsx');
                    document.body.appendChild(link);
                    link.click();
                });
            });
        },
        //格式化百分比
        formatPercent(row, column, cellValue) {
            // 处理空值和异常值
            if (cellValue === null || cellValue === undefined) return 'N/A';

            // 将小数转换为百分比
            if (typeof cellValue === 'number') {
                return (cellValue * 100).toFixed(2) + '%';
            }

            // 处理字符串类型的百分比值
            if (typeof cellValue === 'string') {
                const numValue = parseFloat(cellValue);
                if (!isNaN(numValue)) {
                    return (numValue * 100).toFixed(2) + '%';
                }
            }

            return cellValue; // 无法转换时返回原始值
        },
        // 数字千分位格式化
        formatNumber(row, column, cellValue) {
            if (cellValue === null || cellValue === undefined) return '0'
            // 如果是字符串且包含百分号，直接返回（避免对百分比进行千分位处理）
            if (typeof cellValue === 'string' && cellValue.includes('%')) {
                return cellValue
            }
            // 转换为数字
            const num = Number(cellValue)
            // 处理NaN情况
            if (isNaN(num)) return cellValue
            // 使用toLocaleString添加千分位
            return num.toLocaleString('en-US')
        },
        //查询
        query() {
            const year = '20' + this.queryParams.selectedYear.slice(-2) + '-'
            const selectedMonths = [];
            if (this.queryParams.selectedMonths != []) {
                for (let index = 0; index < this.queryParams.selectedMonths.length; index++) {
                    selectedMonths.push(year + this.queryParams.selectedMonths[index]);
                }
            }
            querytable(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.selectedYear, selectedMonths, this.queryParams.selectedLines).then(response => {
                this.total = response.total
                this.tableData = response.list

            })
        },
        //获取当前年
        shortYear() {
            const year = new Date().getFullYear();
            const lyear = (year % 100) - 2;
            this.queryParams.selectedYear = "F" + (year % 100);
            for (let index = 0; index < 5; index++) {
                this.years.push("F" + (lyear + index))
            }
        },
        // 导入Excel
        handleImport(file) {
            this.importLoading = true;
            this.loading = true;
            this.loadingText = '正在导入数据...';

            const formData = new FormData();
            formData.append("file", file.raw);

            importExcel(formData)
                .then(response => {
                    this.$modal.msgSuccess(response.msg);
                })
                .catch(error => {
                    this.$modal.msgError(error);
                })
                .finally(() => {
                    this.importLoading = false;
                    this.loading = false;
                });
        },

        // 下载导入模板
        downloadTemplate() {
            this.templateLoading = true;
            this.loading = true;
            this.loadingText = '正在下载模板...';

            exportctTemplate()
                .then(res => {
                    // 处理blob下载
                    const blob = new Blob([res], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = '数据导入模板.xlsx';
                    link.click();

                    // 显示成功消息
                    this.$modal.msgSuccess('模板下载成功');
                })
                .catch(error => {
                    this.$modal.msgError('模板下载失败: ' + error);
                })
                .finally(() => {
                    this.templateLoading = false;
                    this.loading = false;
                });
        }
    }
};
</script>

<style scoped>
#app {
    font-family: 'Helvetica Neue', Arial, sans-serif;
    /* background-color: #f0f2f5; */
    color: #333;
    padding: 20px;
    min-height: 100vh;
    position: relative;
}

.filter-container {
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 25px;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 25px;
    margin-bottom: 15px;
}

.filter-group {
    flex: 1;
    min-width: 250px;
}

.filter-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #555;
}

.chart-body {
    padding: 15px;
    flex: 1;
    /* 使图表区域填充剩余空间 */
    min-height: 280px;
    /* 最小高度保证一致性 */
}

.chart-container {
    width: 100%;
    height: 100%;
}

.action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 15px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
    .chart-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        /* 中等屏幕每行2个 */
    }
}

@media (max-width: 900px) {
    .chart-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        /* 小屏幕每行2个 */
    }
}

@media (max-width: 768px) {
    .chart-grid {
        grid-template-columns: 1fr;
        /* 移动端每行1个 */
    }

    .filter-row {
        flex-direction: column;
        gap: 15px;
    }

    .filter-group {
        min-width: 100%;
    }

    .action-buttons {
        flex-wrap: wrap;
        justify-content: center;
    }

    .action-buttons .el-button {
        flex: 1;
        min-width: 120px;
    }
}

.hard-buttons {
    height: 35px;
}

/* 加载效果样式 */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.85);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    backdrop-filter: blur(3px);
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 4px solid rgba(64, 158, 255, 0.2);
    border-top: 4px solid #409EFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

.loading-text {
    font-size: 16px;
    font-weight: 600;
    color: #409EFF;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>